package logic

import (
	"context"
	"fmt"
	"shopping-mall/models/mysql"
	"shopping-mall/models/redis"

	"shopping-mall/shoppingrpc/internal/svc"
	"shopping-mall/shoppingrpc/shoppingrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type UserLoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewUserLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLoginLogic {
	return &UserLoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *UserLoginLogic) UserLogin(in *shoppingrpc.UserLoginRequest) (*shoppingrpc.UserLoginResponse, error) {
	// todo: add your logic here and delete this line

	var user mysql.User

	code := in.SmsCode

	get := redis.Rdb.Get("sendSmslogin" + in.Mobile)

	if get.Val() != code {
		return nil, fmt.Errorf("短信验证码输入有误")
	}
	err := mysql.Db.Debug().Where("mobile = ?", in.Mobile).Find(&user).Error
	if err != nil {
		return nil, err
	}
	if user.ID == 0 {
		return nil, fmt.Errorf("用户不存在")
	}
	if user.Password != in.Password {
		return nil, fmt.Errorf("密码错误")
	}
	redis.Rdb.Del("sendSmslogin" + in.Mobile)

	return &shoppingrpc.UserLoginResponse{Id: int64(user.ID)}, nil
}
